import React, { Component } from 'react'
import { connect } from 'react-redux';
import { commentReq } from '@/utils/request'
import { ALLBLOGCHANGE } from '@/store/actionType'
import { Comment, Avatar, Form, Button, List, Input, Divider, Skeleton, message } from 'antd';
import { DeleteOutlined } from '@ant-design/icons'
import moment from 'moment';// moment().fromNow()
const { TextArea } = Input;

const CommentList = ({ comments, deleteFunc, skeletonLoading, email }) => (
  <List
    dataSource={comments}
    // 条数
    header={`${comments.length} ${comments.length > 1 ? 'replies' : 'reply'}`}
    itemLayout="horizontal"
    // 当使用 dataSource 时，可以用 renderItem 自定义渲染列表项; Comment是引入antd
    renderItem={item => (
      // 每一条评论
      <List.Item
        key={item.datetime}
        actions={[<span>{moment(item.datetime).fromNow()}</span>,
        item.author === email && <Button onClick={() => deleteFunc(item.author, item.datetime)} icon={<DeleteOutlined />}></Button>]}
      >
        <Skeleton avatar title={false} loading={skeletonLoading} active>
          <List.Item.Meta
            avatar={
              <Avatar src={item.avatar || '/topaz-blog/qq.jpg'} alt={item.email} />
            }
            title={item.author}
            description={item.content}
          />
          {/* <div>{item.content}</div> */}
        </Skeleton>
      </List.Item>
    )}
  />
);

// redux
const mapStateToProps = (state, ownProps) => {
  return {
    avatar: state.getIn(['user', 'obj', 'avatar']),
    email: state.getIn(['user', 'obj', 'email'])
  }
}
const mapDispatchToProps = {
  setComment: (data) => {
    return commentReq(data).then((res) => {
      const payload = res.result && res.result.length > 0 ? res.result : []
      return {
        type: ALLBLOGCHANGE,
        payload
      }
    })
  }
}
@connect(mapStateToProps, mapDispatchToProps)
class CommentItem extends Component {
  constructor(props) {
    super(props)
    this.state = {
      submitting: false,
      value: '',
      skeletonLoading: false
    }
  }

  handleSubmit = () => {
    const { id, commentNum, avatar, email } = this.props
    const { value } = this.state
    const obj = {
      author: email,
      avatar: avatar,
      content: value,
      datetime: new Date().getTime(),
    }
    // 为空不上传
    if (!value.trim()) {
      return;
    }
    // 防抖
    this.setState({ submitting: true })
    // 上传
    this.props.setComment({
      id,
      commentList: [...commentNum, obj]
    }).then(() => {
      this.setState({ submitting: false,value: '' })
    })
  };

  // 得到输入内容
  handleChange = e => {
    this.setState({
      value: e.target.value,
    });
  };

  // 删除
  deleteFunc = (author, datetime) => {
    const { id, commentNum, email } = this.props
    if (email === author) {
      const newList = commentNum.filter(item => item.datetime !== datetime)
      this.props.setComment({
        id,
        commentList: [...newList]
      }).then(() => {
        message.success({ duration: 1, content: '删除成功' })
      })
    }
  }

  componentDidMount() {
    this.setState({ skeletonLoading: false })
  }

  render() {
    const { submitting, value, skeletonLoading } = this.state;
    const { commentNum, avatar, email } = this.props
    return (
      <div>
        {/* 分割线 */}
        <Divider orientation="left">留言区</Divider>
        {/* 留言列表 */}
        {commentNum.length > 0 && <CommentList skeletonLoading={skeletonLoading} deleteFunc={this.deleteFunc} comments={commentNum} email={email} />}
        {/* 发送留言 */}
        <Comment
          avatar={
            <Avatar
              src={avatar || '/topaz-blog/qq.jpg'}
              alt={email}
            />
          }
          content={
            <div>
              <Form.Item>
                <TextArea autoSize={{ minRows: 2, maxRows: 3 }} onChange={this.handleChange} value={value} />
              </Form.Item>
              <Form.Item>
                <Button loading={submitting} onClick={this.handleSubmit} type="primary">
                  留言
                </Button>
              </Form.Item>
            </div>
          }
        />
      </div>
    );
  }
}
export default CommentItem
